package com.amaake.server;

import com.amaake.utils.RpcService;
import com.amaake.utils.ClassUtils;
import com.google.common.collect.Lists;
import com.jfinal.kit.StrKit;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Amaake
 * \* Date: 2016/11/16 0016
 * \* Time: 20:07
 * \* Description: 春眠不觉晓，起来敲代码。
 * \
 */
public class RpcServiceLists {

    private List<String> includeClassPaths = Lists.newArrayList();
    protected final Logger logger = Logger.getLogger(getClass());
    private Map<String, Object> proxyMaps = new HashMap<String,Object>();
    private boolean ifsearch = false;

    public boolean setIsIfsearch(boolean ifsearch){
        this.ifsearch = ifsearch;
        return this.ifsearch;
    }

    public void addIncludePaths(String... paths) {
        for (String path : paths) {
            includeClassPaths.add(path);
        }
    }

    public Map<String, Object> getProxyMaps(){
        return proxyMaps;
    }

    public void addService(Class o)throws IllegalAccessException, InstantiationException{
        RpcService rpcService = (RpcService) o.getAnnotation(RpcService.class);
        proxyMaps.put(rpcService.value(),o.newInstance());
    }

    public void init() {
        if(ifsearch){
            List<Class> serviceClasses = null;
            for(String path : includeClassPaths){
                if(serviceClasses==null){
                    serviceClasses = ClassUtils.scanPackage(path);
                }else{
                    serviceClasses.addAll(ClassUtils.scanPackage(path));
                }
            }
            RpcService rpcService = null;
            for (Class service : serviceClasses) {
                rpcService = (RpcService) service.getAnnotation(RpcService.class);
                if (rpcService == null) {
                    continue;
                } else if (StrKit.notBlank(rpcService.value())) {
                    try {
                        proxyMaps.put(rpcService.value(),service.newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

//    public static void main(String[] args)throws IllegalAccessException, InstantiationException{
//        RpcServiceLists rpcServiceLists = new RpcServiceLists();
//        rpcServiceLists.setIsIfsearch(true);
//        rpcServiceLists.addIncludePaths("com.amaake.service");
//        rpcServiceLists.init();
//        Map<String, Object> map = rpcServiceLists.getProxyMaps();
//        System.out.println(map.size());
//        IndexService indexService = (IndexServiceImp)map.get("index");
//        indexService.index();
//    }
}